package com.computergames.server.protocol;

import com.computergames.server.config.Config;
import com.computergames.server.message.LoginRequestMessage;
import com.computergames.server.message.Message;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.util.List;

public class TestMessageCodec {
    public static void main(String[] args){
        MessageCodecSharable messageCodec = new MessageCodecSharable();
        LoggingHandler loggingHandler = new LoggingHandler(LogLevel.INFO);
        EmbeddedChannel channel = new EmbeddedChannel(loggingHandler, messageCodec, loggingHandler);

        LoginRequestMessage message = new LoginRequestMessage("zhangsan", "123");
        //channel.writeOutbound(message);
        ByteBuf byteBuf = messageToByte(message);
        channel.writeInbound(byteBuf);
    }
    public static ByteBuf messageToByte(Message message){
        int algorithm = Config.getSerializerAlgorithm().ordinal();
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
        //1. 4字节的魔数
        byteBuf.writeBytes(new byte[]{'c','g','c','p'});
        //2. 1字节的协议版本
        byteBuf.writeByte(1);
        //3. 1字节的序列化方式 jdk 0， json 1
        byteBuf.writeByte(algorithm);
        //4. 1字节的指令类型
        byteBuf.writeByte(message.getMessageType());
        //5. 4字节的请求序号，提供异步能力
        byteBuf.writeInt(message.getSequenceId());
        // 无意义，对齐填充凑齐16字节
        byteBuf.writeByte(0xff);
        //6. 获取内容的字节数组
        byte[] bytes = Config.getSerializerAlgorithm().serialize(message);
        //7. 长度
        byteBuf.writeInt(bytes.length);
        //8. 写入内容
        byteBuf.writeBytes(bytes);
        return byteBuf;
    }
}
